package admin.web.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import admin.common.enums.ResponseEnum;
import admin.common.constant.AuthConstant;
import admin.common.domain.dto.UserDto;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Objects;

/**
 * @author zgb
 * @date 2024-03-25 17:17
 * @description TODO
 */
public class CurrentUtil {

    public static UserDto currentUserDto(HttpServletRequest request) throws Exception {
        UserDto userDto =null;
                String token = request.getHeader(AuthConstant.JWT_TOKEN_HEADER);
        if (StrUtil.isEmpty(token)) {
            throw new Exception(ResponseEnum.UNAUTHORIZED.getMsg());
        }
        try {
            
            String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
            JWSObject jwsObject = JWSObject.parse(realToken);
            String userStr = jwsObject.getPayload().toString();
            if (StrUtil.isEmpty(userStr)) {
                throw new Exception(ResponseEnum.UNAUTHORIZED.getMsg());
            }
            userDto = JSONUtil.toBean(userStr, UserDto.class);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return userDto;
    }

    /**
     * 管理端获取当前登录人id工具类
     * @return
     */
    public static Long getCurrentUserId(){
        HttpServletRequest request = getRequest();
        String token = request.getHeader(AuthConstant.JWT_TOKEN_HEADER);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        try {
            String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
            JWSObject jwsObject = JWSObject.parse(realToken);
            String userStr = jwsObject.getPayload().toString();
            if (StringUtils.isEmpty(userStr)) {
                throw new Exception(ResponseEnum.UNAUTHORIZED.getMsg());
            }
            UserDto userDto = JSONUtil.toBean(userStr, UserDto.class);
            return userDto.getId();
        } catch (Exception e) {
            return null;
        }
    }


    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }
}
